package com.example.myapplication.util

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF

/**
 * @Author:  zgh
 * @CreateDate:  2023/10/11 16:01
 * @Description: 类功能描述说明
 */
object BitmapUtils {

    /**
     * Return the scaled bitmap.
     *
     * @param src       The source of bitmap.
     * @param newWidth  The new width.
     * @param newHeight The new height.
     * @return the scaled bitmap
     */
    fun scale(src: Bitmap, newWidth: Int, newHeight: Int): Bitmap? {
        return scale(src, newWidth, newHeight, false)
    }

    /**
     * Return the scaled bitmap.
     *
     * @param src       The source of bitmap.
     * @param newWidth  The new width.
     * @param newHeight The new height.
     * @param recycle   True to recycle the source of bitmap, false otherwise.
     * @return the scaled bitmap
     */
    fun scale(
        src: Bitmap,
        newWidth: Int,
        newHeight: Int,
        recycle: Boolean
    ): Bitmap? {
        if (isEmptyBitmap(src)) return null
        val ret = Bitmap.createScaledBitmap(src, newWidth, newHeight, true)
        if (recycle && !src.isRecycled && ret != src) src.recycle()
        return ret
    }

    /* 获取圆形裁剪的bitmap
     *
     * @param bitmap 原bitmap
     */
    fun getCircleBitmap(srcBitmap: Bitmap): Bitmap {
        val width = srcBitmap.width
        val height = srcBitmap.height
        val squareBitmapWidth = Math.min(width, height)
        val dstBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(dstBitmap)
        val paint = Paint()
        paint.isAntiAlias = true
        val rectF = RectF(0f, 0f, width.toFloat(), height.toFloat())
        canvas.drawOval(rectF, paint)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        val left = (squareBitmapWidth - width) / 2
        val top = (squareBitmapWidth - height) / 2
        canvas.drawBitmap(srcBitmap, left.toFloat(), top.toFloat(), paint)
        srcBitmap.recycle()
        return dstBitmap
    }


    private fun isEmptyBitmap(src: Bitmap?): Boolean {
        return src == null || (src.width == 0) || (src.height == 0)
    }
}